import editForm from "../form.vue";
import Import from "../import.vue";
import ImportRecord from "../import_record.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import {
  deviceDetection,
  cloneDeep,
  isAllEmpty,
  getKeyList
} from "@pureadmin/utils";
import {
  list,
  create,
  update,
  remove,
  importData
} from "@/api/question_answer";

import { reactive, ref, onMounted, h, toRaw } from "vue";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "@/views/common/hooks";
import { useUserStore } from "@/store/modules/user";
import { handleTree } from "@/utils/tree";
import { truncate } from "fs";

export function question_answer(tableRef: Ref) {
  const titleMenu = "配置";
  const userStore = useUserStore();

  const initialForm = {
    search_type: "",
    search: "",
    limit: 20,
    page: 1
  };

  const form = reactive({ ...initialForm });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left"
    },
    {
      label: "id",
      prop: "id"
    },
    {
      label: "类型分类名称",
      prop: "type_classify_title"
    },
    {
      label: "业务分类名称",
      prop: "business_classify_title"
    },
    {
      label: "问题",
      prop: "question"
    },
    {
      label: "答案",
      prop: "answer"
    },
    {
      label: "生成文章次数",
      prop: "generation_count"
    },
    {
      label: "创建时间",
      prop: "created_at"
    },
    {
      label: "操作",
      fixed: "right",
      width: 250,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    form.limit = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const params: Record<string, any> = {
      page: form.page,
      limit: form.limit
    };

    if (form.search_type !== "") {
      if (form.search_type === "generation_count") {
        params[form.search_type] = form.searchMin + "-" + form.searchMax;
      } else {
        params[form.search_type] = form.search;
      }
    }

    const { data } = await list(toRaw(params));

    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.limit;
    pagination.currentPage = data.page;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();

    Object.keys(form).forEach(key => {
      if (!(key in initialForm)) {
        delete form[key];
      }
    });

    Object.assign(form, initialForm);

    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      fullscreenIcon: true,
      title: `${title}${titleMenu}`,
      props: {
        formInline: {
          id: row?.id ?? 0,
          type_classify_id: row?.type_classify_id ?? 0,
          business_classify_id: row?.business_classify_id ?? 0,
          question: row?.question ?? "",
          answer: row?.answer ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了${titleMenu}：${curData.question}`, {
            type: "success"
          });
          done();
          onSearch();
        }
        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              create(curData).then(res => {
                if (res.success) {
                  chores();
                } else {
                  message(res.message, { type: "error" });
                }
              });
            } else {
              update(curData).then(res => {
                if (res.success) {
                  chores();
                } else {
                  message(res.message, { type: "error" });
                }
              });
            }
          }
        });
      }
    });
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  onMounted(async () => {
    onSearch();
  });

  function handleDelete(row) {
    remove({ id: [row.id] }).then(res => {
      if (res.success) {
        message(`您删除了${titleMenu}：${row.question}`, {
          type: "success"
        });
        onSearch();
      } else {
        message(res.message, { type: "error" });
      }
    });
  }

  const selectedNum = ref(0);

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    remove({ id: getKeyList(curSelected, "id") }).then(res => {
      if (res.success) {
        message(`已删除编号为 ${getKeyList(curSelected, "id")} 的数据`, {
          type: "success"
        });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
      } else {
        message(res.message, { type: "error" });
      }
    });
  }

  /** 批量生成文章 */
  function onGenerateArticle() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    generateArticle({ id: getKeyList(curSelected, "id") }).then(res => {
      if (res.success) {
        message(`新闻生成中, 请稍后前往新闻列表查看`, {
          type: "success"
        });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
      } else {
        message(res.message, { type: "error" });
      }
    });
  }

  function handleGenerateArticle(row) {
    generateArticle({ id: [row.id] }).then(res => {
      if (res.success) {
        message(`新闻生成中, 请稍后前往新闻列表查看`, {
          type: "success"
        });
        onSearch();
      } else {
        message(res.message, { type: "error" });
      }
    });
  }

  function handleImport() {
    addDialog({
      fullscreenIcon: true,
      width: "500px",
      title: `导入${titleMenu}`,
      contentRenderer: () => h(Import, { ref: formRef }),
      props: {
        formInline: {
          file: null
        }
      },
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores(res) {
          if (res.success == true) {
            message(`您导入成功了${titleMenu}`, {
              type: "success"
            });
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          } else {
            message(res.message, { type: "error" });
          }
        }
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            const formData = new FormData();
            formData.append("file", curData.file);

            importData(formData).then(res => {
              chores(res);
            });
          }
        });
      }
      //结束
    });
  }

  const handleImportSubmit = async formData => {
    try {
      const response = await importData(formData);
      if (response.code === 200) {
        message("导入成功", { type: "success" });
        onSearch(); // 刷新列表
      } else {
        message(response.message, { type: "error" });
      }
    } catch (error) {
      console.error("导入失败", error);
      message("导入失败", { type: "error" });
    }
  };

  function handleImportRecord() {
    addDialog({
      title: "导入记录",
      width: "1000px",
      fullscreenIcon: true,
      contentRenderer: () => h(ImportRecord)
    });
  }

  return {
    titleMenu,
    form,
    isShow,
    loading,
    columns,
    rowStyle,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleDelete,
    selectedNum,
    onSelectionCancel,
    onbatchDel,
    handleImport,
    formRef,
    handleImportSubmit,
    handleImportRecord,
    onGenerateArticle,
    handleGenerateArticle
  };
}
